package com.kgcx.common.utils;

import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.system.HostInfo;
import com.xiaoleilu.hutool.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@Slf4j
public class SingleTaskUtils {

    /**
     * 检查当前服务是否为第一个
     * 一般用来放在定时任务前检查
     * 因为在某些情况下，定时任务只需要一个服务执行就可以了
     * 注意：这种方法是比较简单的方法，后期考虑改用在DB中存储每个定时任务的执行状态
     * 由各服务检查状态再判断是否执行
     */
    public static void check() {
        List<ServiceInstance> instances = ApplicationUtils.getBean(DiscoveryClient.class).getInstances(ApplicationUtils.getApplicationName());
        if (CollUtil.isNotEmpty(instances)) {
            ServiceInstance instance = instances.get(0);
            String host = instance.getHost();
            HostInfo hostInfo = new HostInfo();
            List<String> networkAddress = getNetworkAddress();
            if (ObjectUtil.notEqual(host, hostInfo.getName()) && ObjectUtil.notEqual(host, hostInfo.getAddress()) && !networkAddress.contains(host)) {
                log.warn("本台机器非集群中的第一台！");
                throw new RuntimeException("本台机器非集群中的第一台！");
            }
        }
    }

    public static List<String> getNetworkAddress() {
        List<String> result = new ArrayList<>();
        Enumeration<NetworkInterface> netInterfaces;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(':') == -1) {
                        result.add(ip.getHostAddress());
                    }
                }
            }
        } catch (Exception e) {
            log.error("", e);
        }
        return result;
    }

}
